//
//  ProfileImageLoadingOperation.m
//  WoWeibo
//
//  Created by  on 12-5-10.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ProfileImageLoadingOperation.h"

@implementation ProfileImageLoadingOperation

@synthesize delegate = _delegate;

- (id)initWithURL:(NSURL *)url indexPath:(NSIndexPath *)indexPath{

    self = [super init];
    
    if(self != nil) {
    
        _url = [url retain];
        _indexPath = [indexPath retain];
    }
    
    return self;
}

- (void)main {

    NSData *data = [NSData dataWithContentsOfURL:_url];
    UIImage *image = [UIImage imageWithData:data];
    
    if(data != nil) {
        
        if(_delegate != nil) {
            
            if([_delegate respondsToSelector:@selector(didDownloadImage:withImage:)]) {
                
                NSMethodSignature *signature = [(id)_delegate methodSignatureForSelector:@selector(didDownloadImage:withImage:)];
                NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
                invocation.target = _delegate;
                invocation.selector = @selector(didDownloadImage:withImage:);
                [invocation setArgument:&_indexPath atIndex:2];
                [invocation setArgument:&image atIndex:3];
                [invocation retainArguments];
                
                [invocation performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:NO];
            }
        }
    }
}

- (BOOL)isConcurrent {

    return YES;
}

- (void)cancel {

    _delegate = nil;
    
    NSLog(@"---");
    
    [super cancel];
}

- (void)dealloc {

    [_url release];
    
    _url = nil;
    
    [super dealloc];
}

@end
